/* Copyright (c) [2025] [zhi1208@126.com]
 * SPDX-License-Identifier: MIT
 */

/*********************
 *      INCLUDES
 *********************/
#include "lvgl.h"
#include "hmi_pg_def.h"

/*********************
 *      DEFINES
 *********************/

/**********************
 *      TYPEDEFS
 **********************/

/**********************
 *  STATIC PROTOTYPES
 **********************/
static hmi_pg_t **locate_pg(hmi_pg_t *pg);

/**********************
 *  STATIC VARIABLES
 **********************/
static lv_ll_t pg_list;

/**********************
 *      MACROS
 **********************/

/**********************
 *   GLOBAL FUNCTIONS
 **********************/
void hmi_pg_manager_init()
{
    lv_ll_init(&pg_list, sizeof(hmi_pg_t *));
}

void hmi_register_pg(hmi_pg_t *pg)
{
    LV_ASSERT_NULL(pg);

    if (locate_pg(pg))
    {
        LV_LOG_WARN("页面【%s】已注册，无法重复注册！", pg->name);
        return;
    }

    hmi_pg_t **node = lv_ll_ins_tail(&pg_list);
    if (!node)
    {
        LV_LOG_WARN("分配内存失败，无法注册页面【%s】！", pg->name);
        return;
    }
    *node = pg;
}

void hmi_log_out_pg(hmi_pg_t *pg)
{
    LV_ASSERT_NULL(pg);

    hmi_pg_t **node = locate_pg(pg);
    if (!node)
    {
        LV_LOG_WARN("页面【%s】未注册，无法注销！", pg->name);
        return;
    }

    lv_ll_remove(&pg_list, node);
    lv_free(node);
}

bool hmi_pg_is_registered(hmi_pg_t *pg)
{
    LV_ASSERT_NULL(pg);

    if (locate_pg(pg))
        return true;

    return false;
}

lv_ll_t *hmi_get_pg_list()
{
    return &pg_list;
}

/**********************
 *   STATIC FUNCTIONS
 **********************/
static hmi_pg_t **locate_pg(hmi_pg_t *pg)
{
    for (hmi_pg_t **node = lv_ll_get_head(&pg_list); node; node = lv_ll_get_next(&pg_list, node))
    {
        if (*node == pg)
            return node;
    }

    return NULL;
}
